from flask import Flask
from multiprocessing import Process
from eval_lib.common import logger
from .auto_test import auto_test_app
from .result import result_app
from .dictionary import dictionary_app
from .cron_job import cron_app_app
from eval_lib.databases.mysql.db import db
from config import conf
from common.const import API_PREFIX, FORWOAD_API_PREFIX
from service.cron_job import CronJobWorker

app = Flask(__name__)
log = logger.get_logger()
app.register_blueprint(auto_test_app, url_prefix=API_PREFIX)
app.register_blueprint(result_app, url_prefix=API_PREFIX)
app.register_blueprint(dictionary_app, url_prefix=API_PREFIX)
app.register_blueprint(auto_test_app, url_prefix=FORWOAD_API_PREFIX)
app.register_blueprint(result_app, url_prefix=FORWOAD_API_PREFIX)
app.register_blueprint(dictionary_app, url_prefix=FORWOAD_API_PREFIX)
app.register_blueprint(cron_app_app, url_prefix=FORWOAD_API_PREFIX)


@app.before_request
def _db_connect():
    if db.is_closed():
        db.connect()


@app.teardown_request
def _db_close(exc):
    if not db.is_closed():
        db.close()


class ServerProcess(Process):

    def __init__(self, queue):
        auto_test_app.queue = queue
        super().__init__()

    def run(self):
        CronJobWorker.init()
        app.run(host="0.0.0.0", port=conf.listen_port)
